package com.aaa.ssm.service.impl;


import com.aaa.ssm.entity.Emp;
import com.aaa.ssm.entity.Login;
import com.aaa.ssm.entity.Permission;
import com.aaa.ssm.mapper.PermissionMapper;
import com.aaa.ssm.mapper.SysMapper;
import com.aaa.ssm.result.AjaxResult;
import com.aaa.ssm.service.SystemService;
import com.aaa.ssm.util.PermissionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lj
 * @date 2021/11/24 19:32
 */
@Service
public class SysServiceImpl implements SystemService {
    @Autowired
    private SysMapper sysMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private HttpSession session;

    @Override
    public AjaxResult login(String username, String password) {

        //账号是否在黑名单中 不在黑名单中验证账号密码是否正确
        Login login = sysMapper.adminLogin(username, password);

        if (login==null){
            return AjaxResult.defeated("账号或密码错误");
        }
        //如果正确 验证账号密码状态是否可用
        if (login.getState()==1){
            return AjaxResult.defeated("员工离职");
        }
        if (login.getState()==2){
            return AjaxResult.defeated("员工账号冻结 请联系管理员");
        }

        //如果可用 则更具账号的id 获取对应的员工信息
        Emp emp = sysMapper.getEmpByID(login.getEid());
        session.setAttribute("emp",emp);
        //生成登录日志 哪个账号 那个IP地址 登陆成功/失败

        return AjaxResult.success();
    }

    @Override
    public AjaxResult getInfo() {
        Emp emp = (Emp) session.getAttribute("emp");

        Map<String, Object> map = new HashMap<>();
        map.put("empInfo",emp);

        //获取员工的角色id
        Integer id = emp.getRole().getId();
        if (id==1){
            List<Permission> adminPers = permissionMapper.getAdminPers();
            map.put("permissions",adminPers);
        }else{
            //查询所有权限 [{m},{c},{c},{m},{c},{c}]
            List<Permission> commonPers = permissionMapper.getCommonPers(id);

            List<Permission> permissions = PermissionUtil.handlePermission(commonPers);

            map.put("permissions",permissions);
        }

        return AjaxResult.success(map);
    }
}
